﻿using DBVisitor.DBProvider;
using Dynamic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBVisitor.Core
{
    public class Row<RowType> : IDisposable where RowType : new ()
	{
		public Table Table { get; private set; }
		private QueryReader QueryReader;
		private static readonly Func<RowType> func = InstanceCreator<RowType>.Create().NoParamsCreator;
		internal Row(Table table, QueryReader queryreader,bool canDispose)
		{
			Table = table;
			QueryReader = queryreader;
			CanDispose = canDispose;
		}
		public void Dispose()
		{
			QueryReader?.Dispose();
			QueryReader = null;
		}
		public T Get<T>(string column, bool dispose = true)
		{
			var value = QueryReader.Get<T>(Table[column]);
			if (dispose&&CanDispose)
				Dispose();
			return value;
		}
		public RowType Parse(bool dispose = true)
		{
			var result = func();
			foreach (var column in Table)
			{
				column.Setter(result, (new DBValue(QueryReader.Reader, column, QueryReader.FieldAccessor, column.RealType)).DeserializeValueObj());
			}
			if (dispose && CanDispose)
				Dispose();
			return result;
		}
		private readonly bool CanDispose;
    }
}
